package entrata;

import classi.faLogin;
import classi.utente;
import com.mysql.jdbc.Connection;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet nella quale viene fatto il login
 * @author sestari
 */
public class login extends HttpServlet {

    /**
     * Gestione dei cookies
     * 
     * @param request
     * @param response
     * @param user
     * @return 
     */
    public String cookies(HttpServletRequest request, HttpServletResponse response, utente user) {

        String data = "";
        try {

            //Prendi la data dell'ultimo accesso
            Cookie[] cookies = request.getCookies();
            int len = cookies.length;
            for (int i = 0; i < len; i++) {
                Cookie c1 = cookies[i];
                if (c1.getName().equals("dataUltimoAcesso" + user.getId())) {
                    data = c1.getValue();
                }

            }

            //inserisce la data attuale
            faLogin fl = new faLogin();
            Cookie c = new Cookie("dataUltimoAcesso" + user.getId(), fl.getDateTime());
            c.setMaxAge(10000);
            response.addCookie(c);

            if (data.equalsIgnoreCase("")) {
                data = "Prima registrazione!";
            } else {
                data = "Ultimo accesso il: " + data;
            }

        } catch (Exception e) {
            System.out.print("cjfejifhasjhfa");
        }



        return data;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            try {
                ServletContext sc = getServletContext();
                Connection con = (Connection) sc.getAttribute("con");



                String user = request.getParameter("user");
                String pass = request.getParameter("pass");



                faLogin fl = new faLogin(con);
                utente uten = fl.Login(user, pass);

                //Verifica se l'utente e' valido
                if (uten != null) {
                    HttpSession session = request.getSession();
                    session.setAttribute("user", uten);
                    session.setAttribute("Ultimoacesso", cookies(request, response, uten));

                    response.sendRedirect("welcome");
                } else {
                    response.sendRedirect("index.html?msg=Username o Password sbagliati!");

                }


            } finally {
                out.close();
            }

        } catch (Exception e) {
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String msg = request.getParameter("msg");


        PrintWriter out = response.getWriter();



        index(out, msg);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Genera la pagina index.html 
     * 
     * @param out
     * @param msg 
     */
    public void index(PrintWriter out, String msg) {
        out.println("<html> ");
        out.println("    <head> ");
        out.println("        <title>Login</title> ");
        out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> ");
        out.println("    </head> ");
        out.println("    <body> ");
        out.println("        <div>SISTEMA RR</div> ");

        out.println("        <br> ");
        out.println("        <br> ");
        if (msg != null) {
            out.println(msg);
        }
        out.println("        <br> ");
        out.println("        <br> ");
        out.println("        <div>  ");
        out.println("            <form action=\"index.html\" method=\"post\"> ");
        out.println("                <table border=\"0\"> ");
        out.println("                    <tr> ");
        out.println("                        <td>Username: </td> ");
        out.println("                        <td> <input type=\"text\" name=\"user\" />                          ");
        out.println("                    </tr> ");
        out.println("                    <tr> ");
        out.println("                        <td>Password: </td> ");
        out.println("                        <td> <input type=\"password\" name=\"pass\" />                          ");
        out.println("                    </tr> ");
        out.println("                    <tr> ");
        out.println("                        <td> ");
        out.println("                            <input type=\"submit\"  value=\"Entrare\"/> ");
        out.println("                        </td> ");
        out.println("              </form> ");
        out.println("                        <td> ");
        out.println("                            <form action=\"registrarePaziente\" method=\"get\"> ");
        out.println("                                <input type=\"submit\" value=\"Creare Account!\"/> ");
        out.println("                            </form> ");
        out.println("                        </td> ");
        out.println("                </table> ");
        out.println("                <br> ");
        out.println("                <br> ");
        out.println("                </div> ");
        out.println("                </body> ");
        out.println("                </html> ");

    }
}
